﻿import gtk
import os
import sys
import socket
import SocketServer
import G
import threading
import multiprocessing
import time

class MyTcpHandler(SocketServer.BaseRequestHandler):
            def handle(self):
                self.data=self.request.recv(10240).strip()
                
                #print "recieve from server: "+"\r\n"+self.data+"\r\n"
                print "\r\n"+self.data.strip()+"\r\n"
                #print "Test"
                G.SMSG=self.data+"\r\n"+G.SMSG
                #time.sleep(0.2)
                #print G.SMSG
                G.TBuffer.set_text(G.SMSG.strip())
                #if os.path.exists(r'c:\tmp.data')==False:
                #        f=open(r'c:\tmp.data','w')
                #        f.write("\r\n"+self.data+"\r\n")
                #        f.close()
                #else:
                #        f=open(r'c:\tmp.data','a')
                #        f.write("\r\n"+self.data+"\r\n")
                                
class MyClient(gtk.Window):
        def __init__(self):
                super(MyClient,self).__init__()

                self.set_title("MyClient")
                self.set_size_request(250, 270)
                self.set_position(gtk.WIN_POS_CENTER)

                vbox = gtk.VBox(False, 2)

                lbl_smsg=gtk.Label("服务器消息")
                lbl_smsg.set_size_request(250,20)
                
                self.smsg=gtk.TextView()
                G.TBuffer = self.smsg.get_buffer()
                self.smsg.set_size_request(250,180)
                self.smsg.set_editable(False)
                self.smsg.unset_flags(gtk.CAN_FOCUS)
                
                scroll = gtk.ScrolledWindow()
                scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
                scroll.add(self.smsg)

                self.entry=gtk.Entry()
                self.connect("key_press_event",self.on_keypress)
                

                btnSend=gtk.Button("发送")
                btnSend.connect("clicked",self.btnSend_click)
                #self.entry.set_editable(True)
                #self.entry.set_flags(gtk.CAN_FOCUS)

                vbox.pack_start(lbl_smsg,False,False)
                vbox.pack_start(scroll,False,False)
                vbox.pack_start(self.entry,False,False)
                vbox.pack_start(btnSend,False,False)

                self.add(vbox)
                
                self.connect("destroy", gtk.main_quit)
                
                #t=threading.Thread(target=startServer)
                #t.daemon=False
                #t.start()

                def tail(file):
                    f=open(file)
                    f.seek(0,2)
                    while True:
                        line=f.readline()
                        if not line:
                            time.sleep(0.1)
                            continue
                        yield line
                        
                def ThreadTail():
                        if os.path.exists(r'c:\tmp.data')==False:
                                f=open(r'c:\tmp.data','w')
                                f.close()
                        lines=tail(r'c:\tmp.data')
                        for line in lines:
                                #print line
                                #G.SMSG=G.SMSG+line
                                G.TBuffer.set_text(G.SMSG.strip())
                                #self.textbuffer.set_text(G.SMSG)

                def DisplayServerMsg():
                        time.sleep(0.1)
                        G.TBuffer.set_text(G.SMSG.replace('/x00',''))

                self.show_all()
                
                #t2=threading.Thread(target=DisplayServerMsg)
                #t2.daemon=False
                #t2.start()
                
                

                #tt=threading.Thread(target=ThreadTail)
                #tt.start()
                
        #lines=tail("C:\Windows\System32\drivers\etc\hosts")

        #for line in lines:
        #    print line
            
        

        def SendMsg(self):
                G.HOSTIP=socket.gethostname()
                host,port=("192.168.0.185",9999)        
                msg=self.entry.get_text()
                self.entry.set_text("")
                #print dir(self.entry)
                if msg.strip()=="clear":
                    G.TBuffer.set_text("")
                    G.SMSG=""
                else:
                    #print "Send:{}".format(msg)+"\r\n"
                    client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                    client.connect((host,port))
                    client.sendall(G.HOSTIP+": "+msg.strip())        
                    data=client.recv(10240)
                    #os.system("cls")
                    
                    #print "recieve from server: "+"\r\n"+data+"\r\n"
                    client.close()
                                

        def btnSend_click(self, widget):
                #print dir(gtk.keysyms)
                self.SendMsg()

        def on_keypress(self, widget, event):
                #if event.keyval == gtk.keysyms.KP_Enter:
                if event.keyval == 65293:
                        self.SendMsg()

def startServer():
    ipaddr=socket.gethostbyname(socket.gethostname())                
    objServer=SocketServer.ThreadingTCPServer((ipaddr,10000),MyTcpHandler)
    print "start server ......"
    objServer.serve_forever()
        
if __name__=="__main__":
    gtk.gdk.threads_init()
    gtk.threads_enter()
    print sys.getdefaultencoding()
    t=threading.Thread(target=startServer)
    t.start()
    MyClient()
    gtk.main()
    gtk.threads_leave()
    
